package com.ly.common.core.bean;

import cn.hutool.http.HttpStatus;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * 响应信息主体
 *
 * @author luoyun
 */
@Data
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@Schema(description = "响应信息主体")
public class R<T> implements Serializable {

    /**
     * 通用成功标识
     */
    public static final Integer SUCCESS = HttpStatus.HTTP_OK;
    public static final Integer FAIL = 500;
    private static final long serialVersionUID = 1L;
    @Schema(description = "成功标志")
    private boolean success = true;

    @Schema(description = "返回标记：成功标记=0，失败标记=1,错误标记=3")
    private int code;

    @Schema(description = "返回信息")
    private String message;

    @Schema(description = "返回数据")
    private T result;

    public static <T> R<T> ok() {
        return restResult(null, SUCCESS, null, true);
    }

    public static <T> R<T> ok(T result) {
        return restResult(result, SUCCESS, null, true);
    }

    public static <T> R<T> ok(T result, String msg) {
        return restResult(result, SUCCESS, msg, true);
    }

    public static <T> R<T> fail() {
        return restResult(null, FAIL, null);
    }

    public static <T> R<T> fail(String msg) {
        return restResult(null, FAIL, msg, false);
    }

    public static <T> R<T> fail(T data) {
        return restResult(data, FAIL, null);
    }

    public static <T> R<T> fail(T data, String msg) {
        return restResult(data, FAIL, msg);
    }

    public static <T> R<T> fail(int code, String msg) {
        return restResult(null, code, msg);
    }

    public static <T> R<T> status(boolean num) {
        return num ? restResult(null, SUCCESS, "操作成功") : restResult(null, FAIL, "操作失败");
    }

    private static <T> R<T> restResult(T data, int code, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setResult(data);
        apiResult.setMessage(msg);
        return apiResult;
    }

    private static <T> R<T> restResult(T result, int code, String message, boolean success) {
        R<T> apiResult = new R<>();
        apiResult.setResult(result);
        apiResult.setCode(code);
        apiResult.setMessage(message);
        apiResult.setSuccess(success);
        return apiResult;
    }
}